<template>
  <div class="custom-search newPublicSideBarSideBar">
    <div class="table-wrap" v-if="!customerOperation">
      <div class="table-wrap-top">
        <div class="table-wrap-top-left">
          <div class="table-wrap-add">
            <span @click="customerAdd"><i class="iconfont icon-zhankai"></i>新建</span>
            <span @click="refresh"><i class="iconfont icon-shuaxin"></i>刷新</span>
          </div>
          <div class="table-wrap-top-search">
            <input-search
              class="table-wrap-top-search-input"
              :placeHolder="search.placeHolder"
              :form="search[activeName].isChildren.nomalForm"
              @quickSearch="handlerQuickSearch"
            ></input-search>
            <advanced-search
              ref="advSearchRef"
              :type="type"
              :pickerName="'customerDate'"
              :adv="search[activeName].isChildren.adv"
              :formItemsConfig="formItemsConfigs[this.activeName]"
              @selectChange="handlerSelectChange"
              @advSearch="advSearch"
              @confirmNewItemsConfig="handleConfirmNewItemsConfig"
            >
            </advanced-search>
            <el-select
              size="mini"
              v-show="showStatusSelect"
              filterable
              v-model.trim="statusSelect"
              class="status-select"
              :placeholder="'请选择客户状态'"
              @change="changeStatus"
            >
              <el-option v-for="(item, index) in statusData" :key="index" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="table-wrap-top-right">
          <pagination
            class="page"
            :small="true"
            :moreFlag="moreFlag"
            :currentPage="currentPage"
            :count="count || 0"
            :showPage="false"
            :allCount="allCount"
            @turnPage="turnPage"
            @getAllCount="getAllCount"
            :totalPage="totalPage"
          >
          </pagination>
        </div>
      </div>
      <div>
        <advSchBadge :badge="search[activeName].isChildren.adv.badgeList" @removeBadge="removeBadge"> </advSchBadge>
      </div>

      <CustomerTable
        ref="customerTable"
        :tableHeader="tableHeader"
        :activeName="activeName"
        :tableData="tableData"
        :searchBoxHeader="searchBoxHeader"
        :isShowCustomerCol="true"
        @operate="operate"
        :qu="qu"
        @selectionchange="selectionchange"
        @selectionall="selectionall"
        @searchBox-change="handleSearchBoxChange"
        :loading="loading"
      ></CustomerTable>
      <div class="batch" :class="{ show: batch[activeName].isBatchShow, navMenuState: navMenuState }">
        <el-checkbox v-model.trim="batch[activeName].allChecked" @change="selectAll">{{
          $t('public.checkAll')
        }}</el-checkbox>
        <card-batch
          v-if="batch[activeName].operator"
          :tabType="activeName"
          :batchOperator="batch[activeName]"
          @checkNone="checkNone"
          @deleteCustomer="deleteCustomer"
          @exportCustomer="exportCustomer"
          @exportCustomerCdr="exportCustomerCdr"
          @exportBatchMonitor="exportBatchMonitor"
          @cancelCustomerContactPlan="cancelCustomerContactPlan"
          @editStatus="editStatus"
          @custConvert="custConvert"
          @assignCustomer="assignCustomer"
        ></card-batch>
      </div>
      <el-dialog
        :close-on-click-modal="false"
        modal-append-to-body
        :title="$t('call.selfDefineName')"
        :visible.sync="defineDialogForm"
        width="50%"
      >
        <el-form>
          <el-input type="text" :rows="2" placeholder="" style="width: 100%" v-model="defaultName"> </el-input>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" class="primary_btn" @click="confirmDownloadMonitor">{{
            $t('public.confirm')
          }}</el-button>
        </div>
      </el-dialog>
      <update-status-dialog :isUpStaDialog="isUpStaDialog" @cancelAndSubmit="upStaDialogClose" :count="batchCount">
      </update-status-dialog>
      <customer-conversion :isCusCvDialog="isCusCvDialog" @cancelAndSubmit="cusCvDialogClose" :count="batchCount">
      </customer-conversion>
      <assign-customer :isAssignDialog="isAssignDialog" @cancelAndSubmit="assignDialogClose" :count="batchCount">
      </assign-customer>
      <ExportDialog
        :isShow="exportDialogIsShow"
        ref="ExportDialog"
        :isHiddenAssociate="true"
        :exportDialogTitle="'导出客户'"
        :exportHeads="exportHeads"
        :isExportTask="isExportTask"
        :isCall="false"
        @exportDialogCancelFun="exportDialogCancelFun"
        @exportDialogDefineFun="exportDialogDefineFun"
        v-if="exportDialogIsShow"
      >
      </ExportDialog>
    </div>
    <div v-else>
      <keep-alive>
        <router-view> </router-view>
      </keep-alive>
    </div>
  </div>
</template>
<script>
import CustomerTable from './CustomerTable.vue'
import Select from '@/components/public-modules/card/search/Select'
import InputSearch from '@/components/public-modules/card/search/InputSearch'
import AdvancedSearch from '@/components/public-modules/card/search/Advanced1Search'
import Pagination from '@/components/public-modules/card/Pagination'
import AdvSchBadge from '@/components/public-modules/card/search/AdvSchBadge'
import CardBatch from '@/components/public-modules/card/CardBatch'
import noviceBoot from '@/components/public-modules/novice-boot/index.vue'
import AssignCustomer from './AssignCustomer'
import UpdateStatusDialog from './UpdateStatusDialog'
import CustomerConversion from './CustomerConversion'
import ExportDialog from '@/components/public-modules/export/exportDialog'
import { deepClone, dateParse, getFormatDateTime, getDateTime } from '@/utils/m7Utils'
import {
  isNotAllowEditCustomerInfo,
  isAllowDeleteCustomer,
  isAllowExportCustomer,
  isAllowAssignCustomer,
  isNotAllowEditStatus,
  isAllowConvertCustomer,
  isAllowExportCustomerCdr,
  isAllowExportBatchMonitor,
  sortCustomFields
} from '@/utils/customerUtils.js'
export default {
  name: 'CustomerSideBarRight',
  data() {
    return {
      showStatusSelect: true, // 自定义搜索是客户状态时，隐藏状态选择项
      isAdvSearchClick: false, // 是否是高级搜索
      tableHeaderMy: [
        { prop: 'name', label: '客户名称' },
        { prop: 'status', label: '客户状态' },
        { prop: 'title', label: '描述' },
        { prop: 'createTime', label: '创建时间' },
        { prop: 'owner', label: '归属人' },
        { prop: 'lastUpdateTime', label: '最近更新时间' },
        { prop: 'contactCus', label: '联系客户' },
        { prop: 'operation', label: '操作', opera: [] }
      ],
      tableHeaderPlan: [
        { prop: 'name', label: '客户名称' },
        { prop: 'status', label: '客户状态' },
        { prop: 'title', label: '描述' },
        { prop: 'notifyTime', label: '联系时间' },
        { prop: 'action', label: '联系内容' },
        { prop: 'createTime', label: '创建时间' },
        { prop: 'owner', label: '归属人' },
        { prop: 'contactCus', label: '联系客户' },
        { prop: 'operation', label: '操作', opera: [] }
      ],
      tableHeaderAll: [
        { prop: 'name', label: '客户名称' },
        { prop: 'status', label: '客户状态' },
        { prop: 'title', label: '描述' },
        { prop: 'createTime', label: '创建时间' },
        { prop: 'owner', label: '归属人' },
        { prop: 'lastUpdateTime', label: '最近更新时间' },
        { prop: 'contactCus', label: '联系客户' },
        { prop: 'operation', label: '操作', opera: [] }
      ],
      defaultTableHeader: {},
      tableData: [],
      checkInit: false,
      isShowCustomerCol: true,
      searchBoxHeader: [],
      customFields: [],
      stableFields: [],
      qu: {},
      loading: true,
      // 最大页数基数
      pages: 0,
      PAGE_SIZE: 10,
      allCount: 0,
      count: 0,
      currentPage: 1,
      moreFlag: false,
      statusData: [],
      statusSelect: '',
      activeName: 'customer_my',
      type: 'customer',
      dbType: '',
      isAssignDialog: false, // 分配客户的弹窗
      isUpStaDialog: false, // 修改状态的弹窗
      isCusCvDialog: false, // 客户转换的弹窗
      exportDialogIsShow: false, // 导出的弹窗
      isExportTask: false, // 导出是否走任务
      defineDialogForm: false, // 自定义导出文件弹窗
      isFirst: null, // 初次进入模块的标识
      batchCount: 0, // 批量操作的number数
      clearChecked: '',
      search: {
        isSearch: false,
        placeHolder: this.$t('customer.enterNameOrPhoneForQuery'),
        customer_my: {
          show: true,
          isChildren: {
            lastQuery: null,
            rel: true,
            select: [],
            nomal: true,
            refresh: true,
            nomalForm: { value: '', query: '' },
            adv: {
              form: {
                categoryId: null,
                status: null,
                name: null,
                phone: null,
                actionType: [],
                custsource1: null,
                province: null,
                city: null,
                lastUpdateTime: [],
                createTime: [],
                batchNo: null,
                notifyTime: [],
                noContactedTime: [],
                CallTime: [],
                noCallTime: [],
                custom: {}
              },
              advSearchOptions: {
                localed: [],
                custom: []
              },
              badgeList: {}
            }
          }
        },
        customer_plan: {
          show: true,
          isChildren: {
            lastQuery: null,
            rel: true,
            select: [],
            nomal: true,
            refresh: true,
            nomalForm: { value: '', query: '' },
            adv: {
              form: {
                categoryId: null,
                status: null,
                name: null,
                phone: null,
                actionType: [],
                custsource1: null,
                province: null,
                city: null,
                district: null,
                lastUpdateTime: [],
                createTime: [],
                batchNo: null,
                noContactedTime: [],
                CallTime: [],
                noCallTime: [],
                notifyTime: [],
                custom: {}
              },
              advSearchOptions: {
                localed: [],
                custom: []
              },
              badgeList: {}
            }
          }
        },
        customer_all: {
          show: true,
          isChildren: {
            lastQuery: null,
            rel: true,
            select: [],
            nomal: true,
            refresh: true,
            nomalForm: { value: '', query: '' },
            adv: {
              form: {
                categoryId: null,
                status: null,
                name: null,
                phone: null,
                actionType: [],
                custsource1: null,
                province: null,
                city: null,
                district: null,
                lastUpdateTime: [],
                createTime: [],
                batchNo: null,
                notifyTime: [],
                ownercom: null,
                owner: null,
                ownerdep: null,
                noContactedTime: [],
                CallTime: [],
                noCallTime: [],
                custom: {}
              },
              advSearchOptions: {
                localed: [],
                custom: []
              }
            },
            badgeList: {}
          }
        }
      },
      formItemsConfigs: {},
      batch: {
        customer_my: {
          batchItem: [],
          allChecked: false,
          isBatchShow: false,
          checkedCount: 0,
          operator: []
        },
        customer_plan: {
          batchItem: [],
          allChecked: false,
          isBatchShow: false,
          checkedCount: 0,
          operator: []
        },
        customer_all: {
          batchItem: [],
          allChecked: false,
          isBatchShow: false,
          checkedCount: 0,
          operator: []
        }
      },
      cusFieldArr: [], // 导出表头
      flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf', // 是否是电商版
      exportTaskLimit: {},
      exportObj: {
        exportFun: null,
        data: null,
        count: 0,
        type: ''
      },
      defaultName: '' // 自定义文件名称
    }
  },
  components: {
    CustomerTable,
    InputSearch,
    AdvancedSearch,
    'v-select': Select,
    Pagination,
    AdvSchBadge,
    CardBatch,
    noviceBoot,
    AssignCustomer,
    UpdateStatusDialog,
    CustomerConversion,
    ExportDialog
  },
  methods: {
    selectAll(data) {
      if (data) {
        this.$refs.customerTable.checkAll()
      } else {
        this.$refs.customerTable.clearSelection()
      }
    },
    customerAdd() {
      this.$store.commit('customer/SET_CUSTOMER_IS_SHOW_BOX', { isShow: true })
      let path = '/index/customer/add'
      this.$router.push({ path: path })
    },
    operate(emitData) {
      if (emitData.action === 'previewFun') {
        this.previewFun(emitData.data)
      } else if (emitData.action === 'deleteFun') {
        this.deleteFun(emitData.data)
      } else if (emitData.action === 'asignwFun') {
        this.isAssignDialog = true
        this.batchCount = 1
        this.batch[this.activeName].batchItem = [emitData.data._id]
      }
      // else if (emitData.action === 'changeStatusFun') {
      //   this.isUpStaDialog = true
      //   this.batchCount = 1
      //   this.batch[this.activeName].batchItem = [emitData.data._id]
      // }
    },
    previewFun(data) {
      this.$store.commit('customer/SET_CUSTOMER_IS_SHOW_BOX', { isShow: true })
      let path = `/index/customer/${this.activeName}/${data._id}`
      this.$router.push({ path: path })
      this.$store.commit('customer/REFRESH_CUST_RIGHT', Math.random())
    },
    deleteFun(data) {
      this.$confirm(`删除后将不可恢复，确定要删除【${data.name}】吗？`, this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        type: 'warning',
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn'
      })
        .then(() => {
          let actionData = { dbType: data.dbType, _id: { $in: [data._id] } }
          this.$store.dispatch('deleteCustomer', actionData).then(() => {
            this.$message({ type: 'success', message: this.$t('customer.deleteCustomerSuccess') })
            this.refresh()
          })
        })
        .catch((err) => {
          console.log(err)
        })
    },
    cusCvDialogClose(obj) {
      // 转移客户弹窗关闭时，发送转移请求
      if (obj.type === 'cancel' || obj.type === 'close') {
        this.isCusCvDialog = obj.bool
        return
      }
      let data = {
        query: {
          dbType: this.dbType
        },
        categoryId: obj.categoryId,
        total: this.batchCount
      }
      if (this.batch[this.activeName].allChecked) {
        Object.assign(data.query, this.transferData(this.search[this.activeName].isChildren.lastQuery))
      } else {
        let ids = this.batch[this.activeName].batchItem
        data.query._id = { $in: ids }
      }
      this.$store.dispatch('batchUpdateCustomerCategory', data).then(() => {
        this.isCusCvDialog = obj.bool
        this.checkNone()
        this.refresh()
        // this.$router.push('/index/customer')
      })
    },
    upStaDialogClose(obj) {
      // 修改状态弹窗关闭时，发送修改请求
      if (obj.type === 'cancel' || obj.type === 'close') {
        this.isUpStaDialog = obj.bool
        return
      }
      let data = {
        query: {
          dbType: this.dbType
        },
        status: obj.status,
        total: this.batchCount
      }

      if (this.batch[this.activeName].allChecked) {
        Object.assign(data.query, this.transferData(this.search[this.activeName].isChildren.lastQuery))
      } else {
        let ids = this.batch[this.activeName].batchItem
        data.query._id = { $in: ids }
      }
      this.$store.dispatch('batchUpdateCustomerStatus', data).then(() => {
        this.isUpStaDialog = obj.bool
        this.checkNone()
        this.refresh()
      })
    },
    assignDialogClose(obj) {
      // 分配客户弹窗关闭时，发送分配的请求
      if (obj.type === 'cancel' || obj.type === 'close') {
        this.isAssignDialog = obj.bool
        return
      }
      let data = {
        query: {
          dbType: this.dbType
        },
        owners: obj.owners
      }
      if (this.batch[this.activeName].allChecked) {
        Object.assign(data.query, this.transferData(this.search[this.activeName].isChildren.lastQuery))
        data.total = this.batchCount
      } else {
        let ids = this.batch[this.activeName].batchItem
        data.query._id = { $in: ids }
        data.total = ids.length
      }
      this.$store.dispatch('assignCustomer', data).then(() => {
        this.isAssignDialog = obj.bool
        this.checkNone()
        this.refresh()
      })
    },
    cancelCustomerContactPlan() {
      // 批量取消联系计划
      if (this.batch[this.activeName].allChecked) {
        this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
          if (resp.success) {
            const _count = resp.count
            let data, count
            if (_count > 10000) {
              this.$message({
                type: 'error',
                message: this.$t('customer.batchUpdateOver10000')
              })
              return
            }
            data = {
              query: {},
              total: _count
            }
            count = _count
            Object.assign(data.query, this.transferData(this.search[this.activeName].isChildren.lastQuery))
            this.cancelContactPlanMessageWithLength(count, data)
          }
        })
      } else {
        let data, count
        let ids = this.batch[this.activeName].batchItem || []
        data = {
          query: {
            _id: { $in: ids }
          },
          total: ids.length
        }
        count = ids.length
        this.cancelContactPlanMessageWithLength(count, data)
      }
    },
    cancelContactPlanMessageWithLength(count, data) {
      this.$confirm(
        this.$t('customer.cancelContactPlanMessageWithLength', { length: count }),
        this.$t('public.cancelPlan'),
        {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }
      )
        .then((v) => {
          return this.$store.dispatch('cancelCustomerContactPlan', data).then(() => {
            // 成功后重置批量选择
            if (this.batch[this.activeName].allChecked) {
              // 全选取消时，要把左侧菜单重置到全部
              this.$emit('routeChangeActiveName', this.activeName)
              this.showStatusSelect = true
            }
            this.checkNone()
            this.refresh()
          })
        })
        .catch((err) => {
          console.log(err)
        })
    },
    selectionchange(selection) {
      let checkedArr = selection.map((item) => item._id)
      this.selectLength = checkedArr.length
      let isBatchShow = checkedArr.length > 0
      let bCheck = checkedArr.length === this.count
      this.$set(this.batch[this.activeName], 'allChecked', bCheck)
      this.batch[this.activeName].batchItem = checkedArr
      this.batch[this.activeName].isBatchShow = isBatchShow
      this.batch[this.activeName].checkedCount = checkedArr.length
    },
    selectionall(arr) {
      this.batch[this.activeName].allChecked = true
      if (this.moreFlag) {
        this.batch[this.activeName].checkedCount = this.batch[this.activeName].allChecked
          ? this.$t('public.moreThan2') + this.count
          : 0
      } else {
        if (this.allCount) {
          this.batch[this.activeName].checkedCount = this.allCount
        } else {
          this.batch[this.activeName].checkedCount = this.batch[this.activeName].allChecked ? this.count : 0
        }
      }
    },
    refresh() {
      this.loading = true
      this.getCustList(this.activeName, this.search[this.activeName].isChildren.lastQuery).then((resp) => {
        this.loading = false
      })
    },
    changeStatus(data) {
      this.currentPage = 1
      // this.$nextTick(() => {
      //   this.$refs.advSearchRef.resetForm()
      // })
      let lastQuery = this.search[this.activeName].isChildren.lastQuery
      if (this.isAdvSearchClick) {
        this.clearSearchQuery()
        const combox = lastQuery.combox
        lastQuery = {
          menu: this.activeName,
          page: 1,
          morePage: 1,
          limit: 10
        }
        if (combox) {
          lastQuery.combox = combox
        }
      }
      // delete lastQuery.combox
      // this.search[this.activeName].isChildren.nomalForm = { value: '', query: '' }
      if (lastQuery && (lastQuery.status === 'totalNotify' || lastQuery.status === 'executor')) {
        lastQuery.customerPlanStatus = data
      } else {
        lastQuery.status = data
      }
      this.search[this.activeName].isChildren.lastQuery = lastQuery
      this.isAdvSearchClick = false
      this.refresh()
    },
    getAllCount() {
      this.allCount = 0
      let form = this.qu
      form.queryCount = true
      form.searchAllCount = true // 此参数是防止vuex的值被改动
      this.getCustList(this.activeName, form).then((resp) => {
        delete this.qu.searchAllCount
        if (resp && resp.success) {
          this.allCount = resp.count
          this.moreFlag = false
        }
        this.loading = false
      })
    },
    getCustList(tabName, query) {
      let _data = deepClone(query)
      _data.queryCount = true
      this.qu = _data
      return this.$store.dispatch('queryCustomerList', query).then((resp) => {
        if (resp && resp.success) {
          // 判定是否是获取真实的count,如果是获取的是真实的count，则不进行处理
          if (!query.queryCount) {
            // 如果返回的列表不为空，则直接保留在当前页，不做任何处理
            // 如果返回的列表为空，则有两种情况，如果有多于 则返回到第一页，否则返回到最后一页
            if (resp.list.length === 0) {
              if (resp.more) {
                this.turnPage(1)
              } else {
                // 算出最后一页的页数
                if (resp.count === 0) {
                  // 第一页且count为0是不再发请求
                  this.currentPage = 1
                } else {
                  let page = Math.ceil(resp.count / query.limit)
                  this.turnPage(page)
                }
              }
            }
            this.tableData = resp.list || []
            this.moreFlag = resp.more
            this.count = resp.count
            this.allCount = resp.count
          }
        } else {
          this.tableData = []
          this.moreFlag = false
          this.count = 0
          this.allCount = 0
        }
        if (query.page === 1) {
          this.pages = this.count / this.PAGE_SIZE
        }
        return resp
      })
    },
    /**
     * [advSearch 高级搜索]
     * @param  {[type]} reset [判断是否重置高级搜索参数]
     * @return {[type]}       [description]
     */
    advSearch(reset) {
      window._hmt && window._hmt.push(['_trackEvent', '其他统计', this.activeName + ' 高级搜索'])
      this.allCount = 0
      this.loading = true
      this.search.initSearch = true
      if (reset) {
        this.clearSearchQuery()
      }
      // 清空快捷搜索字段
      this.statusSelect = ''
      this.search[this.activeName].isChildren.nomalForm.query = ''
      this.search[this.activeName].isChildren.nomalForm.value = ''
      let form = this.search[this.activeName].isChildren.adv.form
      let searchQuery = deepClone(form)
      // 处理deepClone导致Date对象丢失
      for (let key in form.custom) {
        if (form.custom[key] instanceof Date) {
          searchQuery.custom[key] = new Date(form.custom[key].getTime())
        }
      }
      let custom = searchQuery.custom
      let createTime = form.createTime
      let lastUpdateTime = form.lastUpdateTime
      let notifyTime = form.notifyTime
      let noContactedTime = form.noContactedTime
      let noCallTime = form.noCallTime
      let CallTime = form.CallTime
      // 电话
      if (searchQuery.phone) {
        let tel = searchQuery.phone
        searchQuery['phone.tel'] = tel
        delete searchQuery.phone
      }

      // 是否建立联系计划
      if (searchQuery.actionType.length > 0) {
        searchQuery.actionType = searchQuery.actionType[0]
      }

      // 创建时间
      if (createTime) {
        if (createTime[0]) {
          searchQuery.createTime_begin_date = getFormatDateTime(createTime[0])
        }
        if (createTime[1]) {
          searchQuery.createTime_end_date = getFormatDateTime(createTime[1])
        }
        delete searchQuery.createTime
      }

      // 更新时间
      if (lastUpdateTime) {
        if (lastUpdateTime[0]) {
          searchQuery.lastUpdateTime_begin_date = getFormatDateTime(lastUpdateTime[0]).substring(0, 16)
        }
        if (lastUpdateTime[1]) {
          searchQuery.lastUpdateTime_end_date = getFormatDateTime(lastUpdateTime[1]).substring(0, 16)
        }
        delete searchQuery.lastUpdateTime
      }

      // 最近未联系客户时间
      if (noContactedTime) {
        if (noContactedTime[0]) {
          searchQuery.noContactedTime_begin = getFormatDateTime(noContactedTime[0]).substring(0, 16)
        }
        if (noContactedTime[1]) {
          searchQuery.noContactedTime_end = getFormatDateTime(noContactedTime[1]).substring(0, 16)
        }
        delete searchQuery.noContactedTime
      }
      // 最近未通话客户时间
      if (noCallTime) {
        if (noCallTime[0]) {
          searchQuery.noCallTime_begin_date = getFormatDateTime(noCallTime[0]).substring(0, 16)
        }
        if (noCallTime[1]) {
          searchQuery.noCallTime_end_date = getFormatDateTime(noCallTime[1]).substring(0, 16)
        }
        delete searchQuery.noCallTime
      }
      // 通话时间
      if (CallTime) {
        if (CallTime[0]) {
          searchQuery.CallTime_begin_date = getFormatDateTime(CallTime[0]).substring(0, 16)
        }
        if (CallTime[1]) {
          searchQuery.CallTime_end_date = getFormatDateTime(CallTime[1]).substring(0, 16)
        }
        delete searchQuery.CallTime
      }
      // 联系时间
      if (notifyTime) {
        if (notifyTime[0]) {
          searchQuery.notifyTime_begin_date = getFormatDateTime(notifyTime[0])
        }
        if (notifyTime[1]) {
          searchQuery.notifyTime_end_date = getFormatDateTime(notifyTime[1])
        }
        delete searchQuery.notifyTime
      }
      let _customerArr =
        this.search[this.activeName].isChildren.adv &&
        this.search[this.activeName].isChildren.adv.advSearchOptions.custom
      // 自定义字段
      for (let key in custom) {
        // 处理自定义字段中的日期
        if (custom[key] instanceof Array) {
          for (let i = 0; i < _customerArr.length; i++) {
            if (_customerArr[i].name === key && _customerArr[i].inputType === 'date') {
              let _str = ''
              if (custom[key][0]) {
                _str += getDateTime(custom[key][0], 'date')
              }
              if (custom[key][1]) {
                _str += '_' + getDateTime(custom[key][1], 'date')
              }
              searchQuery[key + '_customDate'] = _str
              delete custom[key]
              delete searchQuery[key]
            } else if (_customerArr[i].name === key && _customerArr[i].inputType === 'datetime') {
              let _str = ''
              if (custom[key][0]) {
                _str += getFormatDateTime(custom[key][0])
              }
              if (custom[key][1]) {
                _str += '_' + getFormatDateTime(custom[key][1])
              }
              searchQuery[key + '_customDateTime'] = _str
              delete custom[key]
              delete searchQuery[key]
            } else {
              searchQuery[key] = custom[key]
            }
          }
          continue
        } else {
          searchQuery[key] = custom[key]
        }
      }
      delete searchQuery.custom

      let tempObj = this.advSearchBack(searchQuery)
      this.search[this.activeName].isChildren.adv.badgeList = tempObj

      Object.assign(searchQuery, {
        menu: this.activeName,
        page: 1,
        morePage: 1,
        limit: this.PAGE_SIZE
      })
      this.currentPage = searchQuery.page
      this.search[this.activeName].isChildren.lastQuery = searchQuery
      this.$emit('routeChangeActiveName', this.activeName)
      this.showStatusSelect = true
      this.isAdvSearchClick = true
      this.getCustList(this.activeName, searchQuery).then(() => {
        this.loading = false
      })
    },
    /**
     * [removeBadge description]
     * 移除高级搜索的回显项
     * @return {[type]} [description]
     */
    removeBadge() {
      this.advSearch(true)
      // this.clearChecked = Math.random() + ''
    },
    handleConfirmNewItemsConfig({ data: formItemsConfig, done }) {
      var formItemsConfigs = deepClone(this.formItemsConfigs)
      formItemsConfigs[this.activeName] = formItemsConfig

      this.$store
        .dispatch('saveAdvSearchConfig', {
          searchType: 'CustCardGroup',
          config: formItemsConfigs
        })
        .then(() => {
          this.formItemsConfigs = formItemsConfigs
          done()
        })
    },
    /**
     * [handlerSelectChange description]
     * @param  {[type]} selectObj [
     * selectName 传给后台的属性名
     * selectValue.value  选中的值 => 传给后台
     * selectValue.label 选中的label =>回显的字符串
     * ]
     * @return {[type]}           [description]
     */
    handlerSelectChange(selectObj) {
      let selectName = selectObj.selectName
      let selectValue = selectObj.selectValue
      let form = this.search[this.activeName].isChildren.adv.form
      // 省市的数据拼接
      if (selectName === 'areaLinkage') {
        for (let key in selectValue) {
          form[key] = selectValue[key] ? selectValue[key] : ''
        }
      }
      // 级联的数据处理
      if (selectName === 'cascader') {
        if (selectObj.custom) {
          form.custom[selectObj.name] = selectValue
        } else {
          form[selectObj.name] = selectValue
        }
      }
      // 公海的数据处理
      if (selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') {
        form.ownercom = null
        form.owner = null
        form.ownerdep = null
        form[selectName] = selectValue
      }
    },
    /**
     * [advSearchBack 高级搜索回显]
     * @param  {[type]} searchQuery [需要回显的参数]
     * @return {[type]}             [description]
     */
    advSearchBack(searchQuery) {
      let tmpObj = {}
      for (let key in searchQuery) {
        let value = searchQuery[key]
        if (value && typeof value === 'string') {
          if (value.match(/__/)) {
            let valSplit = value.split('__')
            tmpObj[key] = valSplit[1]
            searchQuery[key] = valSplit[0]
          } else {
            tmpObj[key] = value
          }
        }
        if (value && Array.isArray(value) && value.length > 0) {
          let tmpArr = []
          let tmpArr2 = []
          for (let i = 0; i < value.length; i++) {
            let valSplit = value[i].split('__')
            tmpArr.push(valSplit[1])
            tmpArr2.push(valSplit[0])
          }
          tmpObj[key] = tmpArr.join(' ')
          searchQuery[key] = tmpArr2
        }

        if (value && value.$in && Array.isArray(value.$in) && value.$in.length > 0) {
          let tmpArr = []
          let tmpArr2 = []
          for (let i = 0; i < value.$in.length; i++) {
            let valSplit = value.$in[i].split('__')
            tmpArr.push(valSplit[1])
            tmpArr2.push(valSplit[0])
          }
          tmpObj[key] = tmpArr.join(' ')
          searchQuery[key].$in = tmpArr2
        }

        if (value && value.$in && Array.isArray(value.$in) && value.$in.length === 0) {
          searchQuery[key] = null
        }
      }

      return tmpObj
    },
    routeToMe(isBeforeMount) {
      let query = this.$route.query
      const activeName = query.active || query.addSuccess
      if (activeName) {
        this.$emit('routeChangeActiveName', activeName)
        if (query.id) {
          this.clearSearchQuery()
          this.activeName = activeName
          if (query.selectVal) {
            this.search[this.activeName].isChildren.nomalForm.value = 'executor'
          }
          this.fetchDataQuickSelect(query.selectVal, query.id)
        } else {
          this.activeName = activeName
          if (query.addSuccess) {
            this.$store.commit('customer/SET_CUSTOMER_IS_SHOW_BOX', { isShow: false })
          }
          this.fetchDataQuickSelect()
        }
      } else if (isBeforeMount) {
        this.fetchDataQuickSelect()
      }
    },
    clearSearchQuery() {
      // this.selectVal = ''
      let currentTab = this.search[this.activeName]
      this.currentPage = 1
      for (let key in currentTab.isChildren.adv.form) {
        if (key !== 'custom') {
          if (Array.isArray(currentTab.isChildren.adv.form[key])) {
            currentTab.isChildren.adv.form[key] = []
          } else if (currentTab.isChildren.adv.form.custom[key] && currentTab.isChildren.adv.form.custom[key].$in) {
            currentTab.isChildren.adv.form.custom[key] = { $in: [] }
          } else {
            currentTab.isChildren.adv.form[key] = null
          }
        } else {
          for (let key in currentTab.isChildren.adv.form.custom) {
            if (Array.isArray(currentTab.isChildren.adv.form.custom[key])) {
              currentTab.isChildren.adv.form.custom[key] = []
            } else if (currentTab.isChildren.adv.form.custom[key] && currentTab.isChildren.adv.form.custom[key].$in) {
              currentTab.isChildren.adv.form.custom[key] = { $in: [] }
            } else {
              currentTab.isChildren.adv.form.custom[key] = null
            }
          }
        }
      }
      this.search[this.activeName].isChildren.adv.badgeList = null
      for (let key in this.search[this.activeName].isChildren.nomalForm) {
        this.search[this.activeName].isChildren.nomalForm[key] = null
      }
      this.search[this.activeName].isChildren.lastQuery = null
      this.$nextTick(() => {
        this.$refs.advSearchRef.resetForm()
      })
    },
    turnPage(pageNum) {
      this.allCount = 0
      this.search.isSearch = false
      this.loading = true
      let morePage = pageNum >= this.pages ? Math.floor(pageNum / this.pages + 1) : 1
      this.currentPage = pageNum
      let queryData = Object.assign({}, this.search[this.activeName].isChildren.lastQuery, { page: pageNum, morePage })
      this.search[this.activeName].isChildren.lastQuery.page = pageNum
      this.getCustList(this.activeName, queryData).then(() => {
        this.loading = false
      })
    },
    fetchDataQuickSelect(value, id) {
      this.allCount = 0
      this.loading = true
      // 清除高级搜索项
      this.search[this.activeName].isChildren.adv.badgeList = {}
      this.search.isSearch = true
      this.search[this.activeName].isChildren.nomalForm.value = value
      let query = {
        menu: this.activeName,
        page: 1,
        morePage: 1,
        limit: this.PAGE_SIZE
      }
      if (id) {
        query._id = id
      }
      if (value) {
        Object.assign(query, typeof value === 'object' ? value : { status: value })
      }
      if (this.search[this.activeName].isChildren.nomalForm.query) {
        query.combox = this.search[this.activeName].isChildren.nomalForm.query
      }
      for (let key in query) {
        if (query[key] instanceof Object && !(query[key] instanceof Array)) {
          let date = {}
          for (let datekey in query[key]) {
            if (datekey === 'JGx0') {
              date['$lt'] = query[key][datekey]
            } else if (datekey === 'JGd0') {
              date['$gt'] = query[key][datekey]
            }
          }
          query[key] = date
        }
      }
      this.currentPage = 1
      this.search[this.activeName].isChildren.lastQuery = query
      this.getCustList(this.activeName, query).then((resp) => {
        if (id) {
          if (resp && resp.list.length !== 0) {
            let _id = resp.list[0]._id
            this.previewFun({ _id })
          } else {
            this.$router.push('/index/customer')
            // this.changeTab(this.activeName)
            // this.$store.commit('BLANK', this.activeName)
          }
        }
        this.loading = false
      })
    },
    confirmDownloadMonitor() {
      let data = this.queryData
      delete data.checkRecordExist
      data.fileName = dateParse(new Date()).split('-').join('') + '_' + this.defaultName.trim().replace(/\s/g, '')
      if (!/^[\u4E00-\u9FA5a-zA-Z0-9_.-]*$/.test(data.fileName)) {
        this.$message.error(this.$t('call.symbolForbid'))
        return
      }
      this.defineDialogForm = false
      this.$store.dispatch('addCustomerExportMonitorTask', data).then((rep) => {
        if (rep.success) {
          this.$message({
            message: this.$t('call.exportMonitorTaskSuccess'),
            type: 'success'
          })
          this.checkNone()
        }
      })
    },
    exportCustomer() {
      this.exportHeads = deepClone(this.cusFieldArr)
      this.exportObj.type = 'customerExport'
      this.exportObj.count = 0
      if (this.batch[this.activeName].allChecked) {
        this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
          if (resp.success) {
            this.exportDialogIsShow = true
            const _count = resp.count
            let exportFun = 'exportCustomer'
            let data = {
              Method: 'exportCustomer2In',
              Query: {
                dbType: this.dbType,
                menu: this.activeName
              }
            }
            if (_count > this.exportTaskLimit.customer) {
              this.$message({
                type: 'error',
                message: this.$t('customer.exportCustomerOver1000000', {
                  exportTaskLimit: this.exportTaskLimit.customer
                })
              })
              return
            }
            if (_count > 10000) {
              data.Method = 'exportCustomer'
              exportFun = 'exportCustomerMore'
              this.isExportTask = true
            }
            Object.assign(data.Query, this.transferData(this.search[this.activeName].isChildren.lastQuery))
            this.exportObj.data = data
            this.exportObj.exportFun = exportFun
            this.exportObj.count = _count
          }
        })
      } else {
        let exportFun = 'exportCustomer'
        let data = {
          Method: 'exportCustomer2In',
          Query: {
            dbType: this.dbType,
            menu: this.tabType
          }
        }
        this.exportDialogIsShow = true
        let ids = this.batch[this.activeName].batchItem || []
        data.Query._id = { $in: ids }
        this.exportObj.data = data
        this.exportObj.exportFun = exportFun
      }
    },
    exportDialogCancelFun() {
      this.exportDialogIsShow = false
    },
    exportDialogDefineFun(obj) {
      if (this.exportObj.type === 'customerExport') {
        let exportFun = this.exportObj.exportFun
        let _count = this.exportObj.count
        let data = this.exportObj.data
        data.Query.headers = obj.checkedExportHeads || []
        if (data.Method === 'exportCustomer') {
          data.Query.note = obj.textarea
        }
        this.$store.dispatch(exportFun, data).then(() => {
          this.exportDialogIsShow = false
          if (this.batch[this.activeName].allChecked && _count > 10000) {
            this.$message({
              type: 'success',
              dangerouslyUseHTMLString: true,
              message: this.$t('customer.exportCustomerOver10000', {
                moreOperation: '<span class="iconfont icon-gengduo"></span>'
              })
            })
          }
          // 成功后重置批量选择
          this.checkNone()
        })
      }
    },
    exportBatchMonitor() {
      if (this.batch[this.activeName].allChecked) {
        this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
          if (resp.success) {
            const _count = resp.count
            let data = {
              dbType: this.dbType
            }
            if (_count > 10000) {
              this.$message({
                type: 'error',
                message: this.$t('customer.exportMonitorTaskOver10000')
              })
              return
            }
            Object.assign(data, this.transferData(this.search[this.activeName].isChildren.lastQuery))
            data.checkRecordExist = true
            this.queryData = data
            this.handleAddCustomerExportMonitorTask(data)
          }
        })
      } else {
        let data = {
          dbType: this.dbType
        }
        let ids = this.batch[this.activeName].batchItem || []
        data._id = { $in: ids }
        data.checkRecordExist = true
        this.queryData = data
        this.handleAddCustomerExportMonitorTask(data)
      }
    },
    handleAddCustomerExportMonitorTask(data) {
      this.$store.dispatch('addCustomerExportMonitorTask', data).then((rep) => {
        if (rep.success) {
          let num = ''
          for (let i = 0; i < 19; i++) {
            num += Math.floor(Math.random() * 10).toString()
          }
          let name = this.$store.state.session.user.account + '_' + this.$store.state.session.user.pbx + '_' + num
          this.defaultName = name
          this.defineDialogForm = true
        } else if (rep.message === 'expired_record_exists') {
          this.$message.error(
            this.$t('call.exportOverLimit', { recordStore: rep.recordStore, validStartDate: rep.validStartDate })
          )
        }
      })
    },
    exportCustomerCdr() {
      if (this.batch[this.activeName].allChecked) {
        this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
          if (resp.success) {
            const _count = resp.count
            let data = {
              Method: 'exportCustomerCdr',
              Query: {
                dbType: this.dbType,
                menu: this.activeName
              }
            }
            Object.assign(data.Query, this.transferData(this.search[this.activeName].isChildren.lastQuery))
            if (_count > 1000 && _count <= this.exportTaskLimit.customerCdr_customer) {
              // 导出通话记录大于1000时走任务,上限50000
              this.toCallSheetTask(data)
              return
            } else if (_count > this.exportTaskLimit.customerCdr_customer) {
              this.$message({
                type: 'error',
                message:
                  '最多导出' + this.exportTaskLimit.customerCdr_customer + '个客户的通话记录,请过滤查询条件分多次导出。'
              })
              return
            }
            this.hanldeExportCustomerCdr(data)
          }
        })
      } else {
        let data = {
          Method: 'exportCustomerCdr',
          Query: {
            dbType: this.dbType,
            menu: this.activeName
          }
        }
        let ids = this.batch[this.activeName].batchItem || []
        data.Query._id = { $in: ids }
        this.hanldeExportCustomerCdr(data)
      }
    },
    hanldeExportCustomerCdr(data) {
      data.isKf = true // kf请求这个接口，后台会把上限改成5W的通话记录，否则还是原来的1000
      this.$store.dispatch('exportCustomerCdr', data).then((res) => {
        if (res.success) {
          // 成功后重置批量选择
          this.checkNone()
        } else {
          if (res.callSheetCount) {
            if (res.callSheetCount <= this.exportTaskLimit.customerCdr_call) {
              data.isKf && delete data.isKf
              this.toCallSheetTask(data)
            } else if (res.callSheetCount > this.exportTaskLimit.customerCdr_call) {
              this.$message({
                type: 'error',
                message: '通话详情超过' + this.exportTaskLimit.customerCdr_call + '条上限，请过滤查询条件！'
              })
            }
          }
        }
      })
    },
    toCallSheetTask(data) {
      let actionData = data.Query
      this.$store.dispatch('addCustomerCdrExportTask', actionData).then((resp) => {
        if (resp && resp.success) {
          this.$message({
            type: 'success',
            message: this.$t('call.exportCustomerCallSheetTaskSuccess')
          })
          // 成功后重置批量选择
          this.checkNone()
        } else {
          if (resp && resp.message.indexOf('export_task_max_limit') > -1) {
            this.$message({
              type: 'error',
              message: this.$t('message.export_task_max_limit')
            })
          } else {
            this.$message({
              type: 'error',
              message: this.$t('message.export_task_max_error')
            })
          }
        }
      })
    },
    custConvert() {
      if (this.batch[this.activeName].allChecked) {
        this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
          if (resp.success) {
            const _count = resp.count
            if (_count > 10000) {
              this.$message({
                type: 'error',
                message: this.$t('customer.batchUpdateOver10000')
              })
              return
            }
            this.batchCount = _count
            this.isCusCvDialog = !this.isCusCvDialog
          }
        })
      } else {
        let ids = this.batch[this.activeName].batchItem || []
        this.batchCount = ids.length
        this.isCusCvDialog = !this.isCusCvDialog
      }
    },
    editStatus() {
      if (this.batch[this.activeName].allChecked) {
        this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
          if (resp.success) {
            const _count = resp.count
            if (_count > 10000) {
              this.$message({
                type: 'error',
                message: this.$t('customer.batchUpdateOver10000')
              })
              return
            }
            this.batchCount = _count
            this.isUpStaDialog = !this.isUpStaDialog
          }
        })
      } else {
        let ids = this.batch[this.activeName].batchItem || []
        this.batchCount = ids.length
        this.isUpStaDialog = !this.isUpStaDialog
      }
    },
    assignCustomer() {
      if (this.batch[this.activeName].allChecked) {
        this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
          if (resp.success) {
            const _count = resp.count
            if (_count > 10000) {
              this.batchCount = 10000
            } else {
              this.batchCount = _count
            }
            this.isAssignDialog = !this.isAssignDialog
          }
        })
      } else {
        let ids = this.batch[this.activeName].batchItem || []
        this.batchCount = ids.length
        this.isAssignDialog = !this.isAssignDialog
      }
    },
    handleDeleteCustomer(count, data) {
      let deleteCustomerMessageWithLength = 'customer.deleteCustomerMessageWithLength'
      if (count > 500) {
        deleteCustomerMessageWithLength = 'customer.deleteCustomerMessageWithLength500'
        if (count > 5000) {
          deleteCustomerMessageWithLength = 'customer.deleteCustomerMessageWithLength10000'
        }
        this.delConfirm({
          confirmCentent: deleteCustomerMessageWithLength,
          confirmTitle: 'customer.deleteCustomerRemindOne',
          data: data,
          count,
          del: 'customer.deleteCustomerMessageOne',
          flag: 'next'
        }).then((val) => {
          if (!val) {
            this.delConfirm({
              confirmCentent: deleteCustomerMessageWithLength,
              confirmTitle: 'customer.deleteCustomerRemindTwo',
              data: data,
              count: count,
              del: 'customer.deleteCustomerMessageTwo',
              btn: 'customer.deleteCustomerButtonTwo',
              flag: 'next'
            }).then((val) => {
              if (!val) {
                this.delConfirm({
                  confirmCentent: deleteCustomerMessageWithLength,
                  confirmTitle: 'customer.deleteCustomerRemindThree',
                  data: data,
                  count: count,
                  del: 'customer.deleteCustomerMessageThree',
                  btn: 'customer.deleteCustomerButtonThree',
                  flag: 'lastConfirm'
                })
              }
            })
          }
        })
      } else {
        this.delConfirm({
          confirmCentent: deleteCustomerMessageWithLength,
          confirmTitle: 'customer.deleteCustomer',
          data: data,
          count: count,
          del: 'customer.deleteCustomerMessageOne',
          flag: 'lastConfirm'
        })
      }
    },
    deleteCustomer() {
      if (this.batch[this.activeName].allChecked) {
        this.queryCustomerListCount(this.$store, this.activeName, this.qu).then((resp) => {
          if (resp.success) {
            const _count = resp.count
            let data = {
              dbType: this.dbType
            }
            let count
            let condition = this.search[this.activeName].isChildren.lastQuery
            Object.assign(data, this.transferData(condition))
            count = _count
            this.handleDeleteCustomer(count, data)
          }
        })
      } else {
        let data = {
          dbType: this.dbType
        }
        let count
        let ids = this.batch[this.activeName].batchItem || []
        data._id = { $in: ids }
        count = ids.length
        this.handleDeleteCustomer(count, data)
      }
    },
    delConfirm(data) {
      return this.$confirm(
        this.$t(data.confirmCentent, { length: data.count, next: this.$t(data.del) }),
        this.$t(data.confirmTitle),
        {
          confirmButtonText: this.$t(data.btn) || this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }
      )
        .then((v) => {
          if (data.flag !== 'lastConfirm') {
            return false
          } else {
            return this.$store.dispatch('deleteCustomer', data.data).then(() => {
              // 成功后重置批量选择
              // this.$emit('allCountClear')
              this.checkNone()
              // this.$store.commit('customer/EMPTY_RIGHT')
              this.$message({
                type: 'success',
                message: this.$t('customer.deleteCustomerSuccess')
              })
              this.refresh()
            })
          }
        })
        .catch((err) => {
          if (err === 'cancel') {
            return 'cancel'
          }
        })
    },
    checkNone() {
      this.batch[this.activeName].allChecked = false
      this.batch[this.activeName].batchItem = []
      this.batch[this.activeName].isBatchShow = false
      this.$refs.customerTable.clearSelection()
    },
    transferData(condition) {
      let data = {}
      for (let key in condition) {
        if (condition[key] && (condition[key].length > 0 || (condition[key].$in && condition[key].$in.length))) {
          data[key] = condition[key]
        }
      }
      delete data.page
      delete data.limit
      return data
    },
    queryCustomerListCount(store, tabName, query) {
      return store.dispatch('queryCustomerListCount', query)
    },
    // 快捷搜索 - input
    handlerQuickSearch(value) {
      this.allCount = 0
      this.loading = true
      this.search.isSearch = true
      // 清除高级搜索项
      this.search[this.activeName].isChildren.adv.badgeList = {}
      this.currentPage = 1
      let query = this.search[this.activeName].isChildren.lastQuery
      if (this.isAdvSearchClick) {
        this.clearSearchQuery()
        const status = query.status
        query = {
          menu: this.activeName,
          page: 1,
          morePage: 1,
          limit: 10
        }
        if (status) {
          query.status = status
        }
      }
      query.combox = value || ''
      this.search[this.activeName].isChildren.nomalForm.query = value
      if (this.search[this.activeName].isChildren.nomalForm.value) {
        let selectValue = this.search[this.activeName].isChildren.nomalForm.value
        Object.assign(query, typeof selectValue === 'object' ? selectValue : { status: selectValue })
      }
      this.isAdvSearchClick = false
      this.search[this.activeName].isChildren.lastQuery = query
      this.getCustList(this.activeName, query).then(() => {
        this.loading = false
      })
    },
    getAdvSearchConfig() {
      // 高级搜索自定义布局配置
      this.$store
        .dispatch('getAdvSearchConfig', {
          searchType: 'CustCardGroup'
        })
        .then((configs) => {
          this.formItemsConfigs = configs || {}
        })
    },
    handleLocaledOptions(custTmpl, custCategorysCache) {
      let statuses = [{ label: this.$t('public.all'), value: '' }]
      for (let key in custTmpl.status) {
        statuses.push({ label: custTmpl.status[key], value: `${key}__${custTmpl.status[key]}` })
      }
      let sources = [
        { label: this.$t('public.all'), value: '' },
        { label: this.$t('customer.noSource'), value: `NA__${this.$t('customer.noSource')}` },
        ...custTmpl.source.map((source) => ({ label: source.name, value: `${source.key}__${source.name}` }))
      ]
      let custCategorys = [
        { label: this.$t('public.all'), value: '' },
        ...custCategorysCache.map((category) => ({
          label: category.cName,
          value: `${category._id}__${category.cName}`
        }))
      ]
        let localedOptions = [
          { label: this.$t('customer.categorySource'), filterable: true, name: 'categoryId', inputType: 'select', data: custCategorys },
          { label: this.$t('customer.custStatus'), filterable: true, name: 'status', inputType: 'select', data: statuses },
          { label: this.$t('business.customerName'), name: 'name', inputType: 'input' },
          { label: this.$t('customer.custCall'), name: 'phone', inputType: 'input' },
          { label: this.$t('customer.hasContactPlan'), name: 'actionType', inputType: 'checkbox', data: [{ label: this.$t('public.yes'), value: `date__${this.$t('customer.hasContactPlan')}` }] },
          { label: this.$t('customer.dataSource'), filterable: true, name: 'custsource1', inputType: 'select', data: sources },
          { label: this.$t('public.provinceCity'), name: 'area', inputType: 'area', provinceName: 'province', provinceValue: this.search[this.activeName].isChildren.adv.form.province, cityName: 'city', cityValue: this.search[this.activeName].isChildren.adv.form.city, districtName: 'district', districtValue: this.search[this.activeName].isChildren.adv.form.district },
          { label: this.$t('km.updateTime'), name: 'lastUpdateTime', inputType: 'time' },
          { label: this.$t('public.createTime'), name: 'createTime', inputType: 'time' },
          { label: this.$t('customer.noContactedTime'), name: 'noContactedTime', inputType: 'time' },
          { label: this.$t('customer.noCallTime'), name: 'noCallTime', inputType: 'time' },
          { label: this.$t('customer.CallTime'), name: 'CallTime', inputType: 'time' },
          { label: this.$t('customer.importBatch'), name: 'batchNo', inputType: 'input' },
          { label: this.$t('customer.contactPlan.contactPlanTime'), name: 'notifyTime', inputType: 'time' }
        ]
        return localedOptions
      },
      handleCustomOptions (custTmpl) {
        let customForm = {}
        let customOptions = []
        let sortedCustomFields = sortCustomFields(custTmpl.custom_fields)
        sortedCustomFields.forEach(customField => {
          // 启用的
          if(customField.status !== 'stop') {
            let option = { label: customField.name, name: customField._id }
            if (customField.type === 'single') {
              option.inputType = 'input'
            } else if (customField.type === 'multi') {
              option.inputType = 'textarea'
            } else if (customField.type === 'number') {
              option.inputType = 'input'
              option.validateType = 'Number'
            } else if (customField.type === 'dropdown') {
              if (customField.dic) {
                option.inputType = 'cascader'
                option.data = customField.dic
              } else {
                option.inputType = 'select'
                option.data = []
                for (let key in customField.choices) {
                  let label = customField.choices[key] || ' '
                  option.data.push({ label, value: `${key}__${customField.choices[key]}` })
                }
              }
            } else if (customField.type === 'checkbox' || customField.type === 'radio') {
              option.inputType = customField.type
              option.data = []
              for (let key in customField.choices) {
                option.data.push({ label: customField.choices[key], value: `${key}__${customField.choices[key]}` })
              }
            } else {
              option.inputType = customField.type
            }
  
            customOptions.push(option)
  
            if (customField.type === 'checkbox') {
              customForm[customField._id] = []
            } else if (customField.type === 'date') {
              customForm[customField._id] = ''
            } else if (customField.type === 'dropdown' && !customField.dic) {
              customForm[customField._id] = {$in: []}
            } else {
              customForm[customField._id] = null
            }
          }
        })
        let _obj = {
          customForm: customForm,
          customOptions: customOptions
        }
        return _obj
    },
    getFuncRole() {
      let user = this.$store.state.session.user
      let batchOperators = []
      if (!isNotAllowEditCustomerInfo(user) && isAllowDeleteCustomer(user)) {
        batchOperators.push({ name: 'public.delete', class: 'icon-shanchu', action: 'deleteCustomer' })
      }
      if (isAllowExportCustomer(user)) {
        batchOperators.push({ name: 'public.export', class: 'icon-daochu1', action: 'exportCustomer' })
      }
      if (!isNotAllowEditCustomerInfo(user) && isAllowAssignCustomer(user)) {
        batchOperators.push({ name: 'public.assign', class: 'icon-fenpei', action: 'assignCustomer' })
      }
      if (!isNotAllowEditCustomerInfo(user) && !isNotAllowEditStatus(user)) {
        batchOperators.push({ name: 'public.editStatus', class: 'icon-beizhu', action: 'editStatus' })
      }
      if (!isNotAllowEditCustomerInfo(user) && isAllowConvertCustomer(user)) {
        batchOperators.push({ name: 'public.custConvert', class: 'icon-zhuanhuan', action: 'custConvert' })
      }
      if (isAllowExportCustomerCdr(user)) {
        batchOperators.push({ name: 'public.exportCALL', class: 'icon-daochutonghuajilu', action: 'exportCustomerCdr' })
      }
      if (isAllowExportBatchMonitor(user)) {
        batchOperators.push({ name: 'public.exportTask', class: 'icon-piliang', action: 'exportBatchMonitor' })
      }
      batchOperators.push({
        name: 'public.cancelPlan',
        class: 'icon-quxiaolianxijihua',
        action: 'cancelCustomerContactPlan'
      })
      for (let key in this.batch) {
        if (key !== 'customer_plan') {
          this.batch[key].operator = batchOperators
        } else {
          this.batch[key].operator = [
            { name: 'public.cancelPlan', class: 'icon-quxiaolianxijihua', action: 'cancelCustomerContactPlan' }
          ]
        }
      }
    },
    handleData(custTmpls, custCategorys) {
      if (custTmpls.length <= 0) {
        // 新开的账户，没有数据
        return
      }
      let stableFields = custTmpls[0].stable_fields || []
      for (let i = 0; i < stableFields.length; i++) {
        if (!stableFields[i].isShow) {
          this.cusFieldArr.push({
            name: stableFields[i].name,
            value: stableFields[i].value
          })
        }
        if (stableFields[i].name === 'name') {
          this.tableHeaderMy[0].label = stableFields[i].value
          this.tableHeaderPlan[0].label = stableFields[i].value
          this.tableHeaderAll[0].label = stableFields[i].value
        } else if (stableFields[i].name === 'title') {
          this.tableHeaderMy[2].label = stableFields[i].value
          this.tableHeaderPlan[2].label = stableFields[i].value
          this.tableHeaderAll[2].label = stableFields[i].value
        }
      }
      let _arr = [
        { name: 'owner', value: this.$t('customer.ownerPeople') },
        {
          name: 'ownerNo',
          value: this.$t('webchat.exportHead.agentNum')
        },
        {
          name: 'status',
          value: this.$t('webchat.exportHead.custStatus')
        },
        {
          name: 'source',
          value: this.$t('customer.dataSource')
        },
        {
          name: 'creator',
          value: this.$t('public.creator')
        },
        {
          name: 'createTime',
          value: this.$t('webchat.createTime')
        },
        {
          name: 'lastUpdateTime',
          value: this.$t('monitor.updateTime')
        },
        {
          name: 'attachs',
          value: this.$t('public.attach')
        },
        {
          name: 'sysStatus',
          value: this.$t('customer.sysStatus')
        },
        {
          name: 'categoryId',
          value: this.$t('customer.categoryId')
        },
        {
          name: 'customFields',
          value: this.$t('customer.customField')
        }
      ]
      if (this.flag !== 'ecommerce') {
        _arr.push({ name: 'taskId', value: this.$t('webchat.exportHead.outcallTask') })
        _arr.push({ name: 'taskCalled', value: this.$t('webchat.exportHead.dialState') })
      }
      this.cusFieldArr = [...this.cusFieldArr, ..._arr]
      this.dbType = custTmpls[0]._id
      this.agents = this.$store.getters.agents || {}
      this.custCategorys = custCategorys
    },
    handleAdvData(custTmpls, custCategorysCache) {
      let custTmpl = custTmpls ? custTmpls[0] : {}
      // 处理固定查询字段
      let localedOptions = this.handleLocaledOptions(custTmpl, custCategorysCache)
      let isFieldAdded = (fieldName) =>
        fieldName === 'province' ||
        fieldName === 'city' ||
        fieldName === 'name' ||
        fieldName === 'phone' ||
        fieldName === 'district'
      let stableFieldsDefaultValue = {}
      custTmpl.stable_fields.forEach((stableField) => {
        if (stableField.search && !isFieldAdded(stableField.name)) {
          localedOptions.push({ label: stableField.value, name: stableField.name, inputType: 'input' })
          stableFieldsDefaultValue[stableField.name] = ''
        }
      })
      // 处理自定义字段
      let _obj = this.handleCustomOptions(custTmpl)
      const tabArr = ['customer_my', 'customer_plan', 'customer_all']
      tabArr.forEach((item) => {
        let localedOptionsCopy = deepClone(localedOptions)
        let quickSelect = []
        if (item === 'customer_all') {
          localedOptionsCopy.push({ label: this.$t('customer.owner'), name: 'owner', inputType: 'owner' })
        }
        // 客户状态
        for (let key in custTmpl.status) {
          quickSelect.push({ label: custTmpl.status[key], value: key })
        }
        this.search[item].isChildren.select = quickSelect
        this.search[item].isChildren.adv.form = Object.assign(
          {},
          this.search[item].isChildren.adv.form,
          stableFieldsDefaultValue
        )
        this.search[item].isChildren.adv.advSearchOptions.localed = localedOptionsCopy
        this.search[item].isChildren.adv.advSearchOptions.custom = deepClone(_obj.customOptions)
        this.search[item].isChildren.adv.form.custom = deepClone(_obj.customForm)
      })
    },
    getCustomCol () {
      let data = {
        account: this.$store.state.session.user.account
      }
      const defaultArr = ['name', 'status', 'title', 'createTime', 'owner', 'lastUpdateTime', 'contactCus', 'notifyTime', 'action']
      this.$store.dispatch('getCustomerTemplate', data).then(res => {
        const { data } = res
        if (data.length) {
          this.customFields = data[0].custom_fields.filter(item => item.status === 'run').map(item => {
              item.label = item.name,
              item.name = item._id,
              item.show = false
              return item
          })
          this.stableFields = data[0].stable_fields.map(item => {
            return {
              label: item.value,
              name: item.name,
              show: false
            }
          }).filter(item => {
            return !defaultArr.includes(item.name)
          })
          const defaultCol = this.tableHeader.filter(item => {
            return item.prop !== 'operation'
          }).map(item => {
            return {
              label: item.label,
              name: item.prop,
              show: true
            }
          })
          const source = [{ label: '数据来源', name: 'custsource1', show: false }]
          this.searchBoxHeader = [...defaultCol, ...source, ...this.stableFields, ...this.customFields]
        }
        let sessionId = this.$store.state.session.sessionId
        let cuntomrColFileds = JSON.parse(localStorage.getItem(sessionId + this.activeName + 'cuntomrColFileds'))
        if (cuntomrColFileds) {
          const customerFieldIds = this.customFields.map(item => item._id)
          const catchCustomerFieldsIds = cuntomrColFileds.filter(item => item._id).map(item => item._id)
          // 添加新增
          const newAdd = this.customFields.filter(item => !catchCustomerFieldsIds.includes(item._id) && item._id)
          // 过滤已删除 和 已停用
          cuntomrColFileds = cuntomrColFileds.filter(item => {
            if (item._id) {
              return customerFieldIds.includes(item._id)
            } else {
              return true
            }
          }).concat(newAdd)

          this.searchBoxHeader = [...cuntomrColFileds]
          const result = [...cuntomrColFileds].map(item => {
            item.prop = item.name
            return item
          })
          this.$set(this.defaultTableHeader, this.activeName, result)
        }
      })
    },
    handleSearchBoxChange(dataList, isInit) {
      // 表头配置变化
      if (this.checkInit && isInit === true) {
        // 是否是初始化
        return
      }
      if (isInit === true) {
        this.checkInit = true
      }
      if(isInit) {
        return
      }
      const result = dataList.map(item => {
        item.prop = item.name
        return item
      })
      this.$set(this.defaultTableHeader, this.activeName, result)
      this.searchBoxHeader = [...dataList]
      try{
        let sessionId = this.$store.state.session.sessionId
        window.localStorage.setItem(sessionId + this.activeName + 'cuntomrColFileds',JSON.stringify(this.defaultTableHeader[this.activeName]))
      }catch(err){
        console.log(err)
      }
    }
  },
  deactivated() {
    this.isFirst = false
  },
  activated() {
    if (this.isFirst === null) {
      // 第一次进入组件时 currentPage未null 不执行routeToMe函数，在beforeMount里执行
      return
    }
    this.isFirst = true
    this.routeToMe()
  },
  beforeMount() {
    this.getCustomCol()
    this.getAdvSearchConfig()
    this.exportTaskLimit = this.$getCache('exportTaskLimit') || {}
    let p1 = this.$store.dispatch('getCache', { type: 'custTmpls' })
    let p2 = this.$store.dispatch('getCache', { type: 'agents' })
    let p3 = this.$store.dispatch('getCache', { type: 'custCategorys' })
    Promise.all([p1, p2, p3]).then(([custTmpls, agents, custCategorys]) => {
      this.getFuncRole()
      this.handleAdvData(custTmpls, custCategorys)
      this.handleData(custTmpls, custCategorys)
      if (custTmpls && custTmpls[0]) {
        let arr = [{ label: '全部', value: '' }]
        for (let key in custTmpls[0].status) {
          arr.push({ label: custTmpls[0].status[key], value: key })
        }
        this.statusData = arr
      }
      this.isFirst = true
      this.routeToMe(true)
      this.loading = false
    })
  },
  watch: {
    '$store.state.customer.newCustomerStyle.getCustomerQuery'(newQuery) {
      this.activeName = newQuery.menu
      this.currentPage = 1
      this.clearSearchQuery()
      if (newQuery.status && newQuery.status !== 'totalNotify' && newQuery.status !== 'executor') {
        // 自定义检索是客户状态的，隐藏右侧的客户状态选择
        this.showStatusSelect = false
      } else {
        this.showStatusSelect = true
      }
      this.statusSelect = '' // 清空状态搜索
      this.search[this.activeName].isChildren.nomalForm = { value: '', query: '' } // 清空表单搜索
      for (let key in newQuery) {
        if (newQuery[key] instanceof Object && !(newQuery[key] instanceof Array)) {
          let date = {}
          for (let datekey in newQuery[key]) {
            if (datekey === 'JGx0') {
              date['$lt'] = newQuery[key][datekey]
            } else if (datekey === 'JGd0') {
              date['$gt'] = newQuery[key][datekey]
            }
          }
          newQuery[key] = date
        }
      }
      this.search[this.activeName].isChildren.lastQuery = newQuery
      this.isAdvSearchClick = false
      this.getCustList(newQuery.menu, newQuery).then((resp) => {})
    },
    noticeBusJump() {
      let data = this.$store.state.noticeCustJump
      if (data.module === 'customer' && this.isFirst) {
        this.routeToMe()
      }
    },
    // 客户添加成功跳转到相应的模块
    addSuccess(to) {
      if (to.addSuccess) {
        this.routeToMe()
        let query = {
          menu: to.addSuccess,
          page: 1,
          morePage: 1,
          limit: this.PAGE_SIZE
        }
        this.search[this.activeName].isChildren.lastQuery = query
      }
    },
    activeName() {
      this.getCustomCol()
    }
  },
  computed: {
    addSuccess() {
      return this.$route.query
    },
    noticeBusJump() {
      return this.$store.state.noticeCustJump.random
    },
    totalPage() {
      return Math.ceil(this.count / 10) || 0
    },
    customerOperation() {
      return this.$store.state.customer.newCustomerStyle.showNewCustomerRouterBox
    },
    navMenuState() {
      return this.$store.state.navMenuState || false
    },
    tableHeader() {
      if (this.defaultTableHeader[this.activeName] && this.defaultTableHeader[this.activeName].length) {
        return this.defaultTableHeader[this.activeName].filter(item => {
          return item.show
        }).concat([{ prop: 'operation', label: '操作', opera: [] }])
      } else {
        return this.activeName === 'customer_all' ? this.tableHeaderAll : this.activeName === 'customer_plan' ? this.tableHeaderPlan : this.tableHeaderMy
      }
    },
    customer() {
      if (this.$store.state.customer.current[this.activeName]) {
        return this.$store.state.customer.current[this.activeName]
      } else {
        return {}
      }
    },
  }
}
</script>
<style lang="stylus" scoped>
@import "../../../assets/common.styl"
.custom-export
  label
    visibility visible
    margin 0 15px 15px 0
  .el-checkbox
    visibility visible
  .tips
    margin-bottom 15px
    color $c-prompt
  .checkbox-tooltip
    color $c-prompt
    font-size 14px
  .export-content
    padding 10px 0 20px
  .export-content__item
    display flex
    align-content center
    .export-content__label
      margin-right 15px
  .footer
    text-align center
.batch
  width calc(100vw - 57px - 10px - 188px)
.navMenuState
  width calc(100vw - 312px)
.table-wrap-top
  .table-wrap-top-left
    display flex
    align-items center
  .table-wrap-top-right
    .paginationNew
      position relative
      bottom 0
      box-shadow none
      border-right 0
      background none
  .table-wrap-add
    span
      margin-right 10px
      color #4C9EE8
      font-size 12px
      cursor pointer
      .iconfont
        font-size 12px
  .table-wrap-top-search-input
    margin 0
  display flex
  justify-content space-between
  align-items center
  margin-bottom 10px
  .table-wrap-top-search
    display flex
    align-items center
    position relative
.custom-search
  height 100%
h4
  line-height 40px
  border-bottom 1px solid $c-border1
  padding-left 10px
  font-weight bold
.table-wrap
  padding 30px 20px
</style>
<style lang="stylus">
.newPublicSideBarSideBar
  .toggle-btn
    line-height: 28px
    width: 26px
    border: 1px solid #dcdfe6
    height: 30px
    display: inline-block
    box-sizing: border-box
    top: 1px
    color: #9a9a9a
    text-align: center
    margin-left: -1px
    background-color: #fff
    border-radius: 0 4px 4px 0
    cursor: pointer
  .status-select
    margin-left 20px
</style>
